import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { getWeatherHistory } from 'utils/Api'
import { toast } from 'react-toastify'

const HOC = (WrappedComponent) => {
  class HighComponent extends Component {
    constructor(props) {
      super(props)
      this.state = {
        echart: null,
      }
    }
    componentDidMount() {

      this.echart2 = echarts.init(this.echart)
      
      window.addEventListener('resize', () => {
        this.echart2.resize({
          width: 'auto'
        })
      })
      this.update()
      this.echart2.resize({
        width: document.querySelector('.echart').offsetWidth - 400+'px'
      })
    }

    update = () => {
      const { landId, startDate, endDate, type } = this.props
      this.echart2.showLoading({
        text: '加载中',
        color: '#c23531',
        textColor: '#000',
        maskColor: '#fff',
        zlevel: 0,
      })
      getWeatherHistory({
        landId,
        type,
        startDate: startDate.format('YYYY/MM/DD'),
        endDate: endDate.format('YYYY/MM/DD'),
      })
        .then(({ msg, result }) => {
          if (msg === '200') {
            this.echart2.hideLoading()
            this.setState({
              result,
              echart: this.echart2
            })
          }
        })
    }
    componentDidUpdate(prevProps, prevState) {
      const { leftCollapsed, rightCollapsed } = this.props
      const { result, echart } = this.state
     
      if (!result) {
        return
      }
      if (leftCollapsed !== prevProps.leftCollapsed) {
        echart.resize({
          width: document.querySelector('.echart').offsetWidth + (leftCollapsed ? 150 : (-150)) + 'px'
        })
        return
      }
      if (rightCollapsed !== prevProps.rightCollapsed) {
        echart.resize({
          width: document.querySelector('.echart').offsetWidth + (rightCollapsed ? 250 : (-250)) + 'px'
        })
        return
      }
      const { startDate, endDate } = this.props
      if (!prevProps.startDate.isSame(startDate) || !prevProps.endDate.isSame(endDate)) {
        this.update()
        return
      }

    }
    render() {
      const { result } = this.state
      const { type } = this.props
      return <div>
        {result && <WrappedComponent {...this.state} {...this.props} />}
        <div id={type} className='echart' ref={echart => this.echart = echart}></div>
      </div>
    }
  }
  HighComponent.propTypes = {
    leftCollapsed: PropTypes.bool,
    rightCollapsed: PropTypes.bool,
    landId: PropTypes.string,
    startDate: PropTypes.object,
    endDate: PropTypes.object,
    type: PropTypes.string,
    unit: PropTypes.bool,
    dateChangeEnd: PropTypes.bool,
  }
  return HighComponent
}

export default HOC